package com.example.demo.controller;

import cn.hutool.json.JSONObject;
import com.example.demo.entity.*;
import com.example.demo.service.*;
import com.example.demo.util.GetMessage;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.*;

@RestController
@RequestMapping("/api/train")
@RequiredArgsConstructor
@Component
public class TrainInfoController {
    @Value("${codeSystem.ip}")
    private String ip;

    private final TrainInfoService trainInfoService;
    private final CodeHistoryService codeHistoryService;
    private final PurchaseApplyOrderService purchaseApplyOrderService;
    private final LogisticsOrderService logisticsOrderService;
    private final MaterialPlanService materialPlanService;
    private final ProducePlanService producePlanService;
    private final PurchaseOrderService purchaseOrderService;

    @CrossOrigin(origins = "*", maxAge = 3600)
    @PostMapping("/submit")
    public GetMessage submitTrain(@RequestBody TrainInfo trainInfo, String userId) {
        TrainInfo trainInfo1=trainInfoService.selectByTrainingid(trainInfo.getTrainingid());
        if(trainInfo1!=null){
            trainInfo.setId(trainInfo1.getId());
            trainInfoService.updateById(trainInfo);
            return new GetMessage("提交成功","200","");
        }else{
            boolean bol=trainInfoService.save(trainInfo);
            if(bol){
                return new GetMessage("提交成功","200",bol);
            }
            return new GetMessage("提交失败","500",bol);
        }
    }

    @CrossOrigin(origins = "*", maxAge = 3600)
    @GetMapping("/select")
    public GetMessage selectByuser(String userId) {
        //String userId=token;
        List<TrainInfo> trainInfo = trainInfoService.selectByUserId(userId);
        if(trainInfo.size()>0){
            return new GetMessage("成功", "200", trainInfo.get(0));
        }
        return new GetMessage("没有训练信息", "500", "");
    }

    @CrossOrigin(origins = "*", maxAge = 3600)
    @PostMapping("/update")
    public GetMessage update(@RequestBody TrainInfo trainInfo) {
        TrainInfo trainInfo1 = trainInfoService.selectByTrainingid(trainInfo.getTrainingid());
        trainInfo.setId(trainInfo1.getId());
        boolean bol = trainInfoService.updateById(trainInfo);
        if (bol) {
            return new GetMessage("修改成功", "200", bol);
        }
        return new GetMessage("修改失败", "500", bol);
    }

    public String getCode(List<CodeHistory> list) {
        String code = "";
        for (CodeHistory c : list) {
            code = code + c.getCodeinfo() + "，";
        }
        return code;
    }
    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @GetMapping("/authon")
    public GetMessage authon(String accesskey,String id,HttpServletResponse response) throws IOException {
        String encodedString = URLEncoder.encode(accesskey, "UTF-8");
        String res=Util.getUrl(ip+"/api/client/authorized-app?owner="+id+"&accessKey="+encodedString,null);
        JSONObject jsonResponse = new JSONObject(res);
        if(jsonResponse.get("code").equals("SUCCESS")){
            TrainInfo trainInfo=trainInfoService.selectByUserId(id).get(0);
            trainInfo.setAccesskey(accesskey);
            trainInfoService.updateById(trainInfo);
            return new GetMessage("成功","200","");
        }else{
            return new GetMessage(jsonResponse.get("message").toString(),"500","");
        }
    }

    @CrossOrigin(origins = "*", maxAge = 3600)
    @GetMapping("/generate")
    public void generateWord(String trainingId, String userName, HttpServletResponse response) {
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("templates/template.docx");

            if (inputStream == null) {
                throw new FileNotFoundException("模板文件未找到！");
            }
            PurchaseApplyOrder p=purchaseApplyOrderService.selectByInfo(null, trainingId, null);
            String str1="";
            String str2="";
            String str8="";
            String str21="";
            String str10="";
            String str6="";
            String str7="";
            if(p!=null){
                str1 = p.getIdentifycode();
            }

            PurchaseOrder purchaseOrder = purchaseOrderService.selectByInfo(null, trainingId, null, null, "0");
            PurchaseOrder purchaseOrder2 = purchaseOrderService.selectByInfo(null, trainingId, null, null, "1");
            if(purchaseOrder!=null){
                str2 = purchaseOrder.getIdentifycode();
                LogisticsOrder logisticsOrder = logisticsOrderService.selectByInfo(null, trainingId, null, null, purchaseOrder.getOrdernumber());
                LogisticsOrder logisticsOrder2 = logisticsOrderService.selectByInfo(null, trainingId, null, null, purchaseOrder2.getOrdernumber());
                if(logisticsOrder!=null){
                    str21 = logisticsOrder.getIdentifycode();
                }
                if(logisticsOrder2!=null){
                    str10 = logisticsOrder2.getIdentifycode();
                }
            }
            if(purchaseOrder2!=null){
                str8 = purchaseOrder.getIdentifycode();
            }

            ProducePlan producePlan = producePlanService.selectByInfo(null, trainingId, null, null, null);
            if(producePlan!=null){
                str6 = producePlan.getIdentifycode();
                MaterialPlan materialPlan=materialPlanService.selectByInfo(producePlan.getPlannumber());
                if(materialPlan!=null){
                    str7 = materialPlan.getIdentifycode();
                }
            }




            String[] titleList = {"用户下单", "生产企业确认订单", "合同确认", "用户财务-付款", "订单转交排产", "排产", "物料需求计划"
                    , "零配件采购", "零配件企业订单确认", "零配件物流下单", "物流企业-物流单确认", "物流企业-物流调度", "物流企业-司机出车"
                    , "零配件出库", "物流装车", "零配件收货入库", "零配件月结", "物料领用", "电视装配", "入库", "准备发货", "出库", "用户入库"};
            String[] titleList1 = {"酒店1_用户下单", "电视工厂2_确认订单", "酒店3_合同确认", "酒店4_用户付款", "电视工厂5_订单转交排产",
                    "电视工厂6_排产", "电视工厂7_物料需求计划", "电视工厂8_零配件采购", "液晶屏工厂9_零配件订单确认", "液晶屏工厂10_物流下单",
                    "物流公司11_物流单确认", "物流公司12_物流调度", "物流公司13_司机出车", "液晶屏工厂14_配件出库", "液晶屏工厂15_物流装车",
                    "电视工厂16_零配件收货入库", "液晶屏工厂17_1_零配件月结_1",
//                    "电视工厂17_2_零配件月结_2", "电视工厂17_3_零配件月结_3",
                    "电视工厂18_物料领用", "电视工厂19_电视装配", "电视工厂20_电视入库", "电视工厂21_准备发货",
                    "电视工厂22_出库","酒店23_用户入库"};
            TrainInfo trainInfo = trainInfoService.selectByTrainingid(trainingId);
            if(trainInfo!=null){
                // 创建 ObjectMapper
                ObjectMapper objectMapper = new ObjectMapper();
                // 解析 JSON 字符串为 JsonNode
                JsonNode jsonNode = objectMapper.readTree(trainInfo.getTaskgroups());

                // 读取文档
                XWPFDocument document = new XWPFDocument(inputStream);

                // 准备替换数据
                Map<String, String> replacements = new HashMap<>();
                replacements.put("{$name}", userName);
                replacements.put("{$date}", LocalDate.now().toString());
                replacements.put("{$score}", trainInfo.getScore().toString());
                Integer totalScore17=0;
                Integer score17=0;
                String ev="";
                for (int i = 0; i < titleList1.length; i++) {
                    String title = titleList1[i];
                    if(title.equals("液晶屏工厂17_1_零配件月结_1")){
                        JsonNode node = jsonNode.get(title);
                        JsonNode node2 = jsonNode.get("电视工厂17_2_零配件月结_2");
                        JsonNode node3 = jsonNode.get("电视工厂17_3_零配件月结_3");
                        totalScore17=Integer.parseInt(node.get("TotalScore").asText())+Integer.parseInt(node2.get("TotalScore").asText())+Integer.parseInt(node3.get("TotalScore").asText());
                        score17=Integer.parseInt(node.get("Score").asText())+Integer.parseInt(node2.get("Score").asText())+Integer.parseInt(node3.get("Score").asText());
                       ev="液晶屏工厂17_1_零配件月结_1的得分是"+node.get("Score").asText()+","+"电视工厂17_2_零配件月结_2的得分是"+node.get("Score").asText()+","+"电视工厂17_3_零配件月结_3的得分是"+node.get("Score").asText();
                    } else{
                        JsonNode node = jsonNode.get(title);
                        if (node != null) {
                            replacements.put("{$stepTotalScore" + (i + 1) + "}", node.get("TotalScore").asText() + "分");
                            replacements.put("{$score" + (i + 1) + "}", node.get("Score").asText() + "分");
                            String str="";
                            JsonNode nodeCell = node.get("Cells");
                            int count = 0;
                            int total = nodeCell.size();
                            if (nodeCell != null && nodeCell.isObject()) {
                                Iterator<Map.Entry<String, JsonNode>> fields = nodeCell.fields();
                                while (fields.hasNext()) {
                                    Map.Entry<String, JsonNode> field = fields.next();
                                    String key = field.getKey();
                                    JsonNode value = field.getValue();

                                    // 构建结果字符串
                                    str = str + key + "的得分是" + value.get("Score").asText();
                                    if (++count < total) {
                                        str = str + "，";
                                    }
                                }
                            }

                            replacements.put("{$evaluation" + (i + 1) + "}", str);
                        }
                    }

                }
                replacements.put("{$stepTotalScore17}", totalScore17 + "分");
                replacements.put("{$score17}", score17 + "分");
                replacements.put("{$evaluation17}", ev);
                replacements.put("{$code1}", str1 + "，" + str2);
                replacements.put("{$code7}", str7);
                replacements.put("{$code8}", str8);
                replacements.put("{$code6}", str6);
                replacements.put("{$code10}", str10);
                replacements.put("{$code21}", str21);
                replacePlaceholders(document, replacements);

                // 设置响应头，返回文件
                response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("实验报告.docx", "UTF-8"));

                OutputStream out = response.getOutputStream();
                document.write(out);

                out.close();
                document.close();
            }else{

            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getEvaluation(JsonNode info,String score,String totalScore) {
        String str = "该部分";
        String info1 = info.asText();
        if (info1 == null || info1.equals("") || info1.equals("null")) {
            if(score.equals(totalScore)){
                str = str + "已完成";
            }else{
                str = str + "未全部完成";
            }

        } else {
            str = str + info.asText();
        }
        return str;
    }

    private static void replacePlaceholders(XWPFDocument document, Map<String, String> replacements) {
        // 处理段落中的占位符
        for (XWPFParagraph paragraph : document.getParagraphs()) {
            replaceInParagraph(paragraph, replacements);
        }

        // 处理表格中的占位符
        for (XWPFTable table : document.getTables()) {
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    for (XWPFParagraph paragraph : cell.getParagraphs()) {
                        replaceInParagraph(paragraph, replacements);
                    }
                }
            }
        }
    }

    private static void replaceInParagraph(XWPFParagraph paragraph, Map<String, String> replacements) {
        List<XWPFRun> runs = paragraph.getRuns();
        if (runs == null || runs.isEmpty()) return;

        StringBuilder text = new StringBuilder();
        for (XWPFRun run : runs) {
            text.append(run.text());
        }

        String originalText = text.toString();
        boolean modified = false;
        for (Map.Entry<String, String> entry : replacements.entrySet()) {
            if (originalText.contains(entry.getKey())) {
                originalText = originalText.replace(entry.getKey(), entry.getValue());
                modified = true;
            }
        }

        if (modified) {
            // 复制第一个 run 的样式
            XWPFRun firstRun = runs.get(0);
            String fontFamily = firstRun.getFontFamily();
            int fontSize = firstRun.getFontSize();
            boolean bold = firstRun.isBold();
            boolean italic = firstRun.isItalic();
            String color = firstRun.getColor();

            // 清空所有 Runs
            for (int i = runs.size() - 1; i >= 0; i--) {
                paragraph.removeRun(i);
            }

            // 新建 Run 并设置样式
            XWPFRun newRun = paragraph.createRun();
            newRun.setText(originalText);
            if (fontFamily != null) newRun.setFontFamily(fontFamily);
            if (fontSize > 0) newRun.setFontSize(fontSize);
            newRun.setBold(bold);
            newRun.setItalic(italic);
            if (color != null) newRun.setColor(color);
        }
    }
}
